package com.sptus.aop;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.sptus.common.constant.CommonConstant;
import com.sptus.common.constant.HttpStatus;
import com.sptus.common.core.redis.RedisCache;
import com.sptus.entity.SptUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
@Component
public class
PermissionAOP {
    @Autowired
    HttpServletResponse response;
    //拦截所有被注解AuthCheck标注的方法
    @Pointcut("@annotation(com.sptus.aop.AppIntercept)")
    public void pointAll(){}

    @Autowired
    public RedisCache redisUtil;

    /**
     *  环绕增强，验证权限
     * @param joinPoint 目标对象
     * @param authCheck 自定义的注解，Around必须这样写，否则自定义的注解无法传入
     * */


    @ResponseBody
    @Around("pointAll() && @annotation(authCheck)")
    public Object before(ProceedingJoinPoint joinPoint, AppIntercept authCheck) throws Throwable {
        //先拿到Request请求体
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        String header = request.getHeader("x-access-token");

        //redis 获取api
        SptUser o = (SptUser) redisUtil.getCacheObject(CommonConstant.PREFIX_EMAIL_USER_TOKEN + header);
        log.info(header);
        System.out.println(o);
        log.info( "");
        if (o!=null){
            Object[] args = joinPoint.getArgs();
            for (int i = 0; i < args.length; i++) {
                if( args[i] instanceof SptUser ){
                    // app 用户赋值
                    SptUser arg = (SptUser) args[i];
                    arg.setId(o.getId());
                    arg.setEmail(o.getEmail());
                }
            }
            return   joinPoint.proceed();
        }

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.SUCCESS);
        final Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("code", HttpStatus.UNAUTHORIZED);
        responseBody.put("error", "Unauthorized");
//        responseBody.put("message", "Unauthorized");
        responseBody.put("path", request.getServletPath());
        final ObjectMapper mapper = new ObjectMapper();

        mapper.writeValue(response.getOutputStream(), responseBody);
        return null;
    }


}
